<template>
  <div class="body">
    <!--    登录界面-->
    <h1 style="text-align: left; margin-top: 7rem">登录</h1>

    <div class="main">
      <a-form
          :model="formState"
          v-bind="layout"
          name="nest-messages"
          :validate-messages="validateMessages"
          @finish="loginOk"
          class="form1"
      >
        <a-form-item :name="['user', 'uno']" label="Account" :rules="[{ required: true }]">
          <a-input v-model:value="formState.user.uno" />
        </a-form-item>
        <a-form-item  :name="['user', 'pwd']" label="Password" :rules="[{min: 4, max: 20 }, {required: true}]">
          <a-input-password  v-model:value="formState.user.pwd" />
        </a-form-item>
        <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 8 }" >
          <a-button class="button" type="primary" html-type="submit" >Submit</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import {onBeforeMount, reactive} from "vue";
import {id_define, login} from "@/api/api";
import {message} from "ant-design-vue";
import router from "@/router";

onBeforeMount(() => {
  const token = localStorage.getItem("token");
  if (token) {
    id_define().then(res => {
      console.log(map[res.data.data.role]);
      router.replace("/" + map[res.data.data.role])
    })
  }
})

const validateMessages = {
  required: '${label} is required!',
  types: {
    email: '${label} is not a valid email!',
  },
  string:{
    range:'${label} must be between ${min} and ${max}!'
  }
};
const formState = reactive({
  //登录
  user: {
    uno: '',
    pwd: '',
    role: 0,
  },
});

// const map = {
//   "1": "admin",
//   "2": "teacher",
//   "3": "student"
// }

const map = ["", "admin", "teacher", "student"]

const loginOk = (values) => {
  // localStorage.removeItem("token");
  const data = {
    uno: values.user.uno,
    pwd: values.user.pwd,
  }
  console.log(data)
  login(data).then((res) => {
    console.log(res.data);
    if(res.data.status !== 200){
      message.error("账号或密码错误")
    }else{
      message.success("登录成功")
      localStorage.setItem("token", res.data.data.token)
      router.push("/" + map[res.data.data.role])
    }
  }, error => {
    console.log(error)
    message.warn("UnKnow")
  })
}

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

</script>

<style scoped>
.body {
  width: 100%;
  height: 5rem;
}
.main {
  width: 100%;
  position: relative;
  border-radius: 20px;
  overflow: hidden;
  transition: transform 0.5s ease, opacity 0.5s ease; /* 添加过渡效果 */
}
.form1 {
  position: relative;
  width: 100%;
}
.button {
  margin-top: 20px;
  margin-left: 40px;
}
.codeGeting{
  background: #cdcdcd;
  border-color: #cdcdcd;
}
</style>
